package com.mengyu.common.base

import android.app.Activity
import android.app.Application
import android.app.Dialog
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.view.WindowManager
import androidx.fragment.app.FragmentActivity


open class BaseActivity: FragmentActivity() {
    // 防止内存泄露，自定义管理Dialog销毁，为什么不使用DialogFragment呢？因为后端到前端恢复会有点问题，暂时不使用这个了
    val listDialog= mutableListOf<Dialog>()
//    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)

    override fun onCreate(savedInstanceState: Bundle?) {
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
//        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
        setCustomDensity(this,application)
        super.onCreate(savedInstanceState)
       // setCustomDensity(this)
    }

      fun setCustomDensity(activity: Activity, application: Application) {
        val appDisplayMetrics = application.resources.displayMetrics
        //360表示这个项目设计图的宽度为360dp
        val targetDensity = (appDisplayMetrics.widthPixels / 360).toFloat() //每dp等于targetDensity px
        val targetDensityDpi = (160 * targetDensity).toInt() //重新计算设备的dpi
        appDisplayMetrics.scaledDensity = targetDensity
        appDisplayMetrics.density = appDisplayMetrics.scaledDensity
        appDisplayMetrics.densityDpi = targetDensityDpi
        val activityDisplayMetrics = activity.resources.displayMetrics
        activityDisplayMetrics.scaledDensity = targetDensity
        activityDisplayMetrics.density = activityDisplayMetrics.scaledDensity
        activityDisplayMetrics.densityDpi = targetDensityDpi
    }

    private fun setCustomDensity(activity: Activity) {

        var activityDisplayMetrics = activity.getResources().getDisplayMetrics();
        var targetDensity = activityDisplayMetrics.widthPixels / 360;
        var targetDensityDpi =   (targetDensity * 160) ;
        activityDisplayMetrics.scaledDensity = targetDensity.toFloat();
        activityDisplayMetrics.density = targetDensity.toFloat()
        activityDisplayMetrics.densityDpi = targetDensityDpi;
    }
    fun showDialog(dialog: Dialog){
        if(!listDialog.contains(dialog)){
            listDialog.add(dialog)
        }
        if(!dialog.isShowing){
            dialog.show()
        }

    }

    fun dismisDialog(dialog: Dialog){
        if(listDialog.contains(dialog)){
            listDialog.remove(dialog)
        }
        if(dialog.isShowing){
            dialog.dismiss()
        }
    }


    override fun onDestroy() {
        if(listDialog.size>0){
            for (dialog in listDialog){
                dialog.dismiss()
            }
            listDialog.clear()
        }
        super.onDestroy()
    }

}